

#include "Object.h"

#include <map>
#include <string>
#include <stdio.h>
#include <stdlib.h>

// Fixme:
// static std::map<std::string, ObjectFactory*> g_map;

class LinkNode {
public:
    std::string     className;
    ObjectFactory*  factory;
    LinkNode*       prev;
    static LinkNode* tail;

    LinkNode() : factory(NULL), prev(NULL) {}
    LinkNode(const char * n, ObjectFactory* f)
        : className(n)
        , factory(f)
        , prev(tail)
    {
        tail = this;
    }

    static LinkNode* find(const char * className) {
        LinkNode* node = tail;
        while (node != NULL) {
            if (node->className == className) {
                return node;
            }
            node = node->prev;
        }
        return NULL;
    }
    static void remove(ObjectFactory* f) {
        LinkNode* node = tail;
        LinkNode* temp = node;
        while (node != NULL) {
            if (node->factory == f) {
                if (node != tail) {
                    temp->prev = node->prev;
                } else {
                    tail = node->prev;
                    temp = tail;
                }
                delete node;
                node = temp;
            }
            temp = node;
            if (node == NULL)
                break;
            node = node->prev;
        }
    }
};

LinkNode* LinkNode::tail = NULL;

ObjectFactory::~ObjectFactory()
{
    unreg();
}

Object* ObjectFactory::createByClassName(const char * name)
{
    LinkNode* node = LinkNode::find(name);
    if (node != NULL) {
        if (node->factory != NULL)
            return node->factory->doCreate();
    }
    return NULL;
}

void ObjectFactory::reg(const char * name)
{
    new LinkNode(name, this);
}

void ObjectFactory::unreg()
{
    LinkNode::remove(this);
}


